package cn.itsource.config.Interceptor;

import cn.itsource.util.AjaxResult;
import cn.itsource.util.BlogConstant;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
@Component  //交给spring管理
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        获得session
        HttpSession session = request.getSession();
//        控制台打印下session值,调试用
        System.out.println("拦截器获取的session的id值：" + session.getId());
//        拿到session中的登录信息
        Object attribute = session.getAttribute(BlogConstant.LOGIN_SESSION);
//        如果没有拿到session信息,则要求用户重新登录
        if (attribute == null) {
//            重新登录
            AjaxResult error = AjaxResult.error(BlogConstant.LOGIN_TIMEOUT, "登录超时,请重新登录");
//            转换为json传给前端(JSONObject.toJSONString是阿里云的fastjson工具包)
//            转换为json字符串
            String s = JSONObject.toJSONString(error);
//            将json字符串转换为json格式
            response.setContentType("application/json;charset=UTF-8");
//            将结果返回
            PrintWriter writer = response.getWriter();
            writer.write(s);
            writer.close();
            return false;
        }
        //4.有效，放行
        return true;
    }
}

